package com.oriole.admin.utils;

import com.oriole.admin.config.local.OrioleUsernamePasswordAuthenticationToken;
import com.oriole.common.constant.Constants;
import com.oriole.common.util.RsaFileUtils;
import com.oriole.common.util.RsaUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import java.security.interfaces.RSAPublicKey;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/8/14 23:50
 * description:
 */
public class SecurityUtils {

    /**
     * 获取token值
     *
     * @return
     */
    public static String getToken() {
        String token = "";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
            token = details.getTokenValue();
        }
        if (authentication instanceof OrioleUsernamePasswordAuthenticationToken) {
            token = authentication.getCredentials().toString();
        }
        return token;
    }

    public static Long getUserId() {
        String token = getToken();
        String publicKey = RsaFileUtils.getContent("public.txt", " PUBLIC KEY");
        RSAPublicKey rsaPublicKey = RsaUtils.getPublicKey(publicKey);
        Claims body = Jwts.parser()
                .setSigningKey(rsaPublicKey)
                .parseClaimsJws(token)
                .getBody();
        Object userId = body.get(Constants.USER_ID);
        return Long.valueOf(userId.toString());
    }
}
